package UDPServer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;
    public int port;

    public UdpEchoServer(int port) throws SocketException {
        //手动指定服务器端口号
        socket = new DatagramSocket(port);
        this.port = port;
    }

    public void start() throws IOException {
        System.out.printf("Server start! ");
        //7*24hs运行
        while (true) {
            //1. 收到请求
            /*byte[] bytes = new byte[1024];
            DatagramPacket requestPacket = new DatagramPacket(bytes, bytes.length);*/
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);//输出型参数
            socket.receive(requestPacket);//等待阻塞
            //将二进制数据转换为字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2. 解析请求
            String response = process(request);
            //3. 发送响应
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    /*response.length() error*/
                    //输入的不是字符串的长度，而是字节数组的长度，否则长度变小，导致输出内容不完整
                    response.getBytes().length,
                    /*requestPacket.getAddress(),requestPacket.getPort() error*/
                    requestPacket.getSocketAddress());//包含客户端IP和端口
            socket.send(responsePacket);
            //4. 打印日志
            System.out.printf("[%s:%d] req: %s,resp: %s\n",
                    requestPacket.getAddress().toString(),responsePacket.getPort(),
                    request,response);
        }
    }


    //暂时是回显服务器，直接把request 当 response 返回
    //以后解析操作只需更改process方法即可
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        //如果跟别人的端口号重复会报错
        UdpEchoServer server = new UdpEchoServer(9191);
        server.start();
    }

}
